﻿using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using Microsoft.Graphics.Canvas.UI;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Numerics;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Effects;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;

namespace TestApp5
{
    public sealed partial class MainPage : Page
    {
        float time;
        CanvasBitmap originalImage;
        byte[] dottedLineCode;

        public MainPage()
        {
            this.InitializeComponent();
        }

        private void CanvasControl_Update(ICanvasAnimatedControl sender, CanvasAnimatedUpdateEventArgs args)
        {
            time = (float)Math.Abs(Math.Sin(args.Timing.UpdateCount));
        }

        private void CanvasControl_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
        {
            IGraphicsEffectSource image = originalImage;
            //IGraphicsEffectSource image = new ScaleEffect
            //{
            //    Scale = new Vector2(6),
            //    Source = originalImage,
            //};
            args.DrawingSession.DrawImage(new PixelShaderEffect(dottedLineCode)
            {
                Source1 = image,
                Properties =
                {
                    ["time"] = time,
                    ["lineWidth"] = sender.Dpi / 96f,
                    ["color1"] = new Vector3(0),
                    ["color2"] =new Vector3(1),
                    ["lineGap"]=100f,
                    ["lineSpeed"] =100f,
                }
            });
        }

        private void CanvasControl_CreateResources(CanvasAnimatedControl sender, CanvasCreateResourcesEventArgs args)
        {
            args.TrackAsyncAction(CreateResourcesAsync().AsAsyncAction());
        }

        private async Task CreateResourcesAsync()
        {
            this.originalImage = await CanvasBitmap.LoadAsync(this.CanvasControl, "Assets/Square150x150Logo.scale-200.png");

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Shader/DottedLine.txt"));
            IBuffer buffer = await FileIO.ReadBufferAsync(file);
            this.dottedLineCode = buffer.ToArray();
        }
    }
}